<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Rust语言从入门到入土 1：Rust的开始, python,machine learning,deep learning,html,css,c,c++,cpp,cmake,ros,linux,ubuntu">
    <meta name="description" content="本文是中科院软件所实习（LARVa项目）日志的第二篇，主要记录了我学习Rust语言的相关内容。本文主要介绍了什么是Rust，以及Rust开发环境配置">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Rust语言从入门到入土 1：Rust的开始 | JackWang&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery-3.6.0.min.js"></script>

<meta name="generator" content="Hexo 5.4.2">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>



   <style>
    body{
       background-image: url(https://cdn.jsdelivr.net/gh/Tokisaki-Galaxy/res/site/medias/background.jpg);
       background-repeat:no-repeat;
       background-size: 100% 100%;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">JackWang&#39;s Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="" class="waves-effect waves-light">

      
      <i class="fas fa-book-reader" style="zoom: 0.6;"></i>
      
      <span>博客</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/tags">
          
          <i class="fas fa-tags" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按标签归类文章</span>
        </a>
      </li>
      
      <li>
        <a href="/categories">
          
          <i class="fas fa-bookmark" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按目录归类文章</span>
        </a>
      </li>
      
      <li>
        <a href="/archives">
          
          <i class="fas fa-archive" style="margin-top: -20px; zoom: 0.6;"></i>
          
	  <span>按日期分类文章</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>



<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">JackWang&#39;s Blog</div>
        <div class="logo-desc">
            
            JackWang的个人博客
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-book-reader"></i>
			
			博客
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/tags " style="margin-left:75px">
				  
				   <i class="fa fas fa-tags" style="position: absolute;left:50px" ></i>
			      
                              <span>按标签归类文章</    span>

                  </a>
                </li>
              
                <li>

                  <a href="/categories " style="margin-left:75px">
				  
				   <i class="fa fas fa-bookmark" style="position: absolute;left:50px" ></i>
			      
                              <span>按目录归类文章</    span>

                  </a>
                </li>
              
                <li>

                  <a href="/archives " style="margin-left:75px">
				  
				   <i class="fa fas fa-archive" style="position: absolute;left:50px" ></i>
			      
                              <span>按日期分类文章</    span>

                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('抱歉，这篇文章并不想让所有人都看到，请输入授权密码观看')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601042403179.png')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Rust语言从入门到入土 1：Rust的开始</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E5%AE%9E%E4%B9%A0%E6%97%A5%E8%AE%B0/">
                                <span class="chip bg-color">实习日记</span>
                            </a>
                        
                            <a href="/tags/%E4%B8%AD%E7%A7%91%E9%99%A2/">
                                <span class="chip bg-color">中科院</span>
                            </a>
                        
                            <a href="/tags/Rust/">
                                <span class="chip bg-color">Rust</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E4%B8%AD%E7%A7%91%E9%99%A2%E5%AE%9E%E4%B9%A0%E6%97%A5%E8%AE%B0/" class="post-category">
                                中科院实习日记
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2023-05-30
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2023-06-04
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    2.7k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    10 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <blockquote>
<p>没办法，还就那个得学一下<code>Rust</code>。本文参考官方教程：<a target="_blank" rel="noopener" href="https://kaisery.github.io/trpl-zh-cn/ch01-00-getting-started.html">https://kaisery.github.io/trpl-zh-cn/ch01-00-getting-started.html</a></p>
</blockquote>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601042403179.png" alt="Rust从入门到入土"></p>
<h2 id="Rust语言从入门到入土-1：Rust的开始"><a href="#Rust语言从入门到入土-1：Rust的开始" class="headerlink" title="Rust语言从入门到入土 1：Rust的开始"></a>Rust语言从入门到入土 1：Rust的开始</h2><p>我对学习的态度是，学习什么之前，得有足够的动力去学习他。所以得先明白他是什么，他有什么用。</p>
<h2 id="1-什么是Rust"><a href="#1-什么是Rust" class="headerlink" title="1. 什么是Rust"></a>1. 什么是Rust</h2><p>简单的介绍，类似于<code>C</code>和<code>C++</code>，<code>Rust</code>是一种系统级编程语言，由<code>Mozilla</code>开发。<strong>它的设计目标是提供一种安全、并发、高效的编程语言，可以用于编写操作系统、网络服务器、嵌入式系统等高性能应用程序</strong>。</p>
<p><code>Rust</code>的语法类似于<code>C++</code>，但它采用了一些新的语言特性，例如所有权系统、借用和生命周期等，这些特性可以帮助程序员避免常见的内存安全问题，例如空指针引用和数据竞争等。<code>Rust</code>还提供了一些高级的并发编程特性，例如通道和闭包等，可以使编写并发程序更加容易和安全。</p>
<p><code>Rust</code>的编译器非常快，并且可以生成高效的本地代码，所以<code>Rust</code>非常适合用于编写高性能的系统级应用程序。</p>
<p>此外，<code>Rust</code>还具有良好的跨平台性，可以在各种操作系统和硬件平台上运行。</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/rust-social-wide.jpg" alt="Rust的Logo" style="zoom: 15%;"></p>
<h2 id="2-Rust无痛开箱"><a href="#2-Rust无痛开箱" class="headerlink" title="2. Rust无痛开箱"></a>2. Rust无痛开箱</h2><blockquote>
<p>学一个新语言，总得先准备好开发环境吧？</p>
</blockquote>
<p><code>Rustup</code>既是一个<code>Rust</code>安装器又是一个版本管理工具，在首次安装<code>Rustup</code>时，就会顺带把<code>Rust</code>的其他工具一起安装了。因此安装<code>Rust</code>的主要方式是通过<code>Rustup</code>这一工具</p>
<p>运行下面的命令安装<code>Rustup</code></p>
<pre class="line-numbers language-bash"><code class="language-bash">curl --proto <span class="token string">'=https'</span> --tlsv1.2 -sSf https://sh.rustup.rs <span class="token operator">|</span> sh
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<blockquote>
<p>PS：<code>curl</code>会去<code>https://sh.rustup.rs</code>这个网站下载安装脚本，所以需要一些魔法。不过我把脚本内容贴在后面了，自己创建一个脚本运行效果也是一样的</p>
</blockquote>
<p>然后开始安装：</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601043831705.png" alt="安装Rustup-1" style="zoom: 25%;"></p>
<p>然后会输出一些关键信息，根据需要选择就好</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601044004907.png" alt="安装Rustup-2" style="zoom:25%;"></p>
<p>稍等片刻，大概喝杯咖啡的功夫就好了。PS：我的魔法不够强大！！！</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601044110177.png" alt="Rustup安装-3" style="zoom:25%;"></p>
<p>最后按照提示添加一下<code>Rust</code>环境激活命令到当前<code>shell</code>的配置文件，然后重新加载配置就好。</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token punctuation">(</span>echo <span class="token string">'source "<span class="token variable">$HOME</span>/.cargo/env"'</span> <span class="token operator">>></span> ~/.zshrc <span class="token operator">&amp;&amp;</span> <span class="token function">source</span> ~/.zshrc <span class="token operator">&amp;&amp;</span> cargo --version<span class="token punctuation">)</span><span class="token operator">||</span> <span class="token keyword">echo</span> <span class="token string">'fail'</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<blockquote>
<p>PS：我用的是<code>zsh</code>，所以是<code>~/.zshrc</code></p>
</blockquote>
<p>安装成功则输出<code>cargo</code>版本，失败则输出<code>fail</code></p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601045254078.png" alt="运气不错，一遍过"></p>
<p>最后，<code>Rust</code>工具链全部在<code>~/.cargo/bin</code>目录下（如果你没修改的话），用<code>ls</code>查看一下</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token function">ls</span> ~/.cargo/bin
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601111035586.png" alt="查看Rust工具链" style="zoom:33%;"></p>
<h2 id="3-Rust开发环境配置"><a href="#3-Rust开发环境配置" class="headerlink" title="3. Rust开发环境配置"></a>3. Rust开发环境配置</h2><blockquote>
<p>当然是宇宙第一编辑器啦！</p>
</blockquote>
<p>在<code>VSCode</code>的扩展，搜索<code>Rust</code>。找到点击<code>install</code>。</p>
<p>或者你更<del>熟悉命令面板</del>（觉得命令面板更酷）的话，按下<code>Command + P</code>，然后输入：<code>ext install rust-lang.rust</code></p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601112844594.png" alt="安装Rust的Language Server" style="zoom: 25%;"></p>
<p>然后创建一个<code>Rust</code>，看看有没有补全</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token punctuation">(</span>cargo new hello_world <span class="token operator">&amp;&amp;</span> code hello_world/main.rs<span class="token punctuation">)</span> <span class="token operator">||</span> <span class="token keyword">echo</span> fail
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>好耶，补全出现，可以开始快乐的写代码了！ヾ(@^▽^@)ノ</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601145814571.png" alt="VSCode成功补全"></p>
<h2 id="4-Rustc和Cargo"><a href="#4-Rustc和Cargo" class="headerlink" title="4. Rustc和Cargo"></a>4. Rustc和Cargo</h2><p><code>Rust</code>类似于<code>C</code>/<code>C++</code>一样，也需要使用编译器将源代码编译为可执行文件，而<code>rustc</code>就是<code>Rust</code>的编译器。除了编写单独的<code>Rust</code>源代码以外，<code>Rust</code>还可以使用<code>Cargo</code>来创建项目。</p>
<h3 id="A-Rustc"><a href="#A-Rustc" class="headerlink" title="A. Rustc"></a>A. Rustc</h3><p>学习一门新语言的时候，使用该语言在屏幕上打印<code>Hello, world!</code>是一项传统，我们将沿用这一传统！</p>
<h4 id="1-创建项目目录"><a href="#1-创建项目目录" class="headerlink" title="1) 创建项目目录"></a>1) 创建项目目录</h4><p>首先创建一个存放<code>Rust</code>代码的目录。<code>Rust</code>并不关心代码的存放位置，不过对于会把<code>Rust</code>代码放到<code>home</code>目录中下的<code>projects</code>目录里的<code>rust-learning</code>目录</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token function">mkdir</span> ~/projects/rust-learning <span class="token operator">&amp;&amp;</span> <span class="token function">cd</span> ~/projects/rust-learning <span class="token operator">&amp;&amp;</span> <span class="token function">mkdir</span> -p hello/hello_<span class="token punctuation">{</span>rustc,cargo_init<span class="token punctuation">}</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<h4 id="2-编写源代码"><a href="#2-编写源代码" class="headerlink" title="2) 编写源代码"></a>2) 编写源代码</h4><p><code>Rust</code>源代码以<code>.rs</code>为后缀，使用下面命令创建一个<code>Rust</code>源代码</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token function">cd</span> hello/hello_rustc <span class="token operator">&amp;&amp;</span> code main.rs
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>然后编写如下的代码</p>
<pre class="line-numbers language-rust"><code class="language-rust"><span class="token keyword">fn</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">println!</span><span class="token punctuation">(</span><span class="token string">"Hello, world!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<h4 id="3-编译可执行文件"><a href="#3-编译可执行文件" class="headerlink" title="3) 编译可执行文件"></a>3) 编译可执行文件</h4><p>类似于<code>gcc</code>，使用<code>Rustc</code>编译<code>Rust</code>源代码</p>
<pre class="line-numbers language-bash"><code class="language-bash">rustc main.rs -o main
<span class="token function">ls</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>得到的<code>main</code>是可执行文件（有<code>x</code>权限）</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601151959110.png" alt="rustc编译Rust源代码" style="zoom: 33%;"></p>
<h4 id="4-运行可执行文件"><a href="#4-运行可执行文件" class="headerlink" title="4) 运行可执行文件"></a>4) 运行可执行文件</h4><p>因为<code>main</code>已经有可执行权限了，并且是二进制程序，所以直接运行即可</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token function">file</span> main
./main
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601152226178.png" alt="运行可执行文件" style="zoom: 33%;"></p>
<h3 id="B-Cargo"><a href="#B-Cargo" class="headerlink" title="B. Cargo"></a>B. Cargo</h3><p>简单的程序，使用 <code>rustc</code> 编译是没问题的，不过随着项目的代码量的增长，项目编译起来就麻烦了。此外，因为项目还可能会依赖第三方的<code>Rust</code>库，因此在使用别人写好的<code>Rust</code>项目的时候还需要注意<code>Rust</code>依赖的问题。</p>
<p><code>Rust</code>提供了一个叫做<code>Cargo</code>的工具，用于帮助我们开发、管理、分享<code>Rust</code>项目。</p>
<h4 id="1-创建项目"><a href="#1-创建项目" class="headerlink" title="1) 创建项目"></a>1) 创建项目</h4><p>使用下面的命令创建一个<code>Cargo</code>管理的<code>Rust</code>项目</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token function">cd</span> ~/project/rust-learning/hello
cargo new hello_cargo_new
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>而后，<code>Cargo</code>会帮助我们创建一个名为<code>hello_cargo_new</code>的<code>Rust</code>项目</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601155002843.png" alt="Cargo创建一个Rust项目" style="zoom: 33%;"></p>
<p><code>Cargo new</code>会创建一个新的目录，如果已经有一个目录，我们想要将这个目录转换为一个<code>Cargo</code>管理的<code>Rust</code>项目的话，那么就是用<code>Cargo init</code></p>
<pre class="line-numbers language-bash"><code class="language-bash">cargo init hello_cargo_init
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601155124688.png" alt="Cargo初始化一个Rust项目" style="zoom: 50%;"></p>
<h4 id="2-项目结构"><a href="#2-项目结构" class="headerlink" title="2) 项目结构"></a>2) 项目结构</h4><p>使用<code>tree</code>查看一下项目的目录结构</p>
<pre class="line-numbers language-bash"><code class="language-bash">tree hello_cargo_new
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601154550783.png" alt="Cargo创建的Rust项目的目录" style="zoom:33%;"></p>
<p>其中：</p>
<ul>
<li><p><code>Cargo.toml</code>是项目的配置文件，使用<code>TOML</code>格式。其中描述了项目名称、使用的<code>Rust</code>版本、依赖的第三方<code>Rust</code>库等等信息。目前因为我们的项目是刚刚初始化的，自然没有任何依赖</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601155405819.png" alt="Cargo.toml的内容" style="zoom:33%;"></p>
</li>
<li><p><code>src</code>目录存放项目的源码</p>
</li>
</ul>
<blockquote>
<p><code>TOML</code>（<code>Tom's Obvious, Minimal Language</code>）是一种易于阅读和编写的配置文件格式，旨在成为配置文件的标准。<code>TOML</code>文件使用简单的语法规则，支持注释、键值对、列表和嵌套数据结构等特性，可以用于配置各种应用程序和工具。</p>
<p><code>TOML</code>文件的语法规则非常简单，其中键值对使用等号或冒号进行赋值，列表使用方括号进行定义，注释使用井号（<code>#</code>）进行标识。下面是一个 <code>TOML</code> 文件的示例：</p>
<pre class="line-numbers language-toml"><code class="language-toml"># This is a TOML document

title = "TOML Example"
description = "An example of TOML file format"

[author]
name = "John Doe"
email = "john@example.com"

[database]
server = "localhost"
port = 3306
username = "root"
password = "password"
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>在上述 <code>TOML</code> 文件中，使用 <code>title</code> 和 <code>description</code> 定义了文档的标题和描述，使用 <code>[author]</code> 和 <code>[database]</code> 定义了两个域。在 <code>[author]</code>域 中，使用 <code>name</code> 和 <code>email</code> 定义了作者的姓名和电子邮件地址，在 <code>[database]</code>域 中，使用 <code>server</code>、<code>port</code>、<code>username</code> 和 <code>password</code> 定义了数据库的连接信息。</p>
<p><code>TOML</code>文件格式的简洁性和易读性，使得它在各种应用程序和工具中得到了广泛的应用，<code>Rust</code> 语言中的 <code>Cargo</code> 包管理工具就使用 <code>TOML</code> 文件来管理项目的依赖关系和构建配置。</p>
</blockquote>
<p>此外，<code>Cargo</code>实际上在创建项目的同时，也会初始化<code>Git</code>仓库</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token function">cd</span> hello_cargo_new <span class="token operator">&amp;&amp;</span> <span class="token function">git</span> status <span class="token operator">&amp;&amp;</span> <span class="token function">ls</span> -a
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601160946541.png" alt="Cargo初始化一个空的Git仓库" style="zoom:33%;"></p>
<h4 id="3-编写源代码"><a href="#3-编写源代码" class="headerlink" title="3) 编写源代码"></a>3) 编写源代码</h4><p>同样，我们还向<code>src/mian.rs</code>中写入输出<code>hello world!</code>的代码</p>
<pre class="line-numbers language-rust"><code class="language-rust"><span class="token keyword">fn</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">println!</span><span class="token punctuation">(</span><span class="token string">"Hello, world!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<blockquote>
<p>注意：<code>Cargo</code>管理的<code>Rust</code>项目预期所以源文件存放在<code>src</code>目录中。项目根目录只存放<code>README</code>、<code>License</code>授权文件、<code>Cargo配置文件</code>和其他<strong>跟代码无关的文件</strong>。我们在编写项目的时候需要注意遵守这一默认的规定以保持项目的整洁</p>
</blockquote>
<h4 id="4-构建项目"><a href="#4-构建项目" class="headerlink" title="4) 构建项目"></a>4) 构建项目</h4><p>类似于<code>CMake</code>和<code>Make</code>这类<code>C</code>/<code>C++</code>项目的编译系统，他们在构建项目的时候可以编译所有源文件、更新目标文件（生成被修改过的源文件的目标文件而不用全部重新编译），<code>Rust</code>也提供了编译系统。</p>
<p>这个编译系统继承进了<code>Cargo</code>中，使用下面的命令编译项目</p>
<pre class="line-numbers language-bash"><code class="language-bash">cargo build
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<blockquote>
<p>注意，<code>cargo build</code>命令需要在项目根目录下运行</p>
</blockquote>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601160809771.png" alt="Cargo build编译项目" style="zoom:33%;"></p>
<p>运行<code>cargo build</code>命令后，<code>Cargo</code>会将编译生成的中间文件、得到的可执行文件<code>debug</code>的目录中。可执行文件的名字就是项目名，我这里就是<code>hello_cargo_new</code>。</p>
<pre class="line-numbers language-bash"><code class="language-bash">tree -d -L 3 ./
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601161617236.png" alt="target/debug目录中存放中间文件" style="zoom:33%;"></p>
<h4 id="5-运行项目"><a href="#5-运行项目" class="headerlink" title="5) 运行项目"></a>5) 运行项目</h4><p>我们可以直接运行得到的可执行文件</p>
<pre class="line-numbers language-bash"><code class="language-bash">./target/debug/hello_cargo_new
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601161728840.png" alt="直接运行可执行文件" style="zoom: 50%;"></p>
<p>不过<code>Cargo</code>提供了<code>cargo run</code>命令，他可以在完成编译后自动运行</p>
<pre class="line-numbers language-bash"><code class="language-bash">cargo run
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601161853363.png" alt="cargo run编译后自动运行" style="zoom:33%;"></p>
<h4 id="6-发布项目"><a href="#6-发布项目" class="headerlink" title="6) 发布项目"></a>6) 发布项目</h4><p><code>cargo build</code>命令编译得到的可执行文件是带有符号表等帮助<code>Debug</code>信息的，使用<code>--release</code>选项来编译不带调试信息的发行版。</p>
<pre class="line-numbers language-bash"><code class="language-bash">cargo build --release
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601162602230.png" alt="编译发布版的项目"></p>
<p>此时生成的中间文件、可执行文件都在<code>target/release</code>目录下</p>
<pre class="line-numbers language-bash"><code class="language-bash">tree -d -L 3 ./
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601162718972.png" alt="target/release目录中存放中间文件" style="zoom:33%;"></p>
<p>因为不带调试信息，<code>release</code>版本的可执行文件小了很多</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token function">ls</span> -alh target/<span class="token punctuation">{</span>debug/hello_cargo_new,release/hello_cargo_new<span class="token punctuation">}</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601162904034.png" alt="release版本比debug版本小4K字节" style="zoom: 50%;"></p>
<h4 id="7-检查项目"><a href="#7-检查项目" class="headerlink" title="7) 检查项目"></a>7) 检查项目</h4><p><code>cargo build</code>会调用<code>Rust</code>编译器，按照编译原理的步骤，一步步进行下去，词法分析、语法分析、语义分析，直到最后生成包含目标平台二进制指令的可执行程序。</p>
<p>但是在写代码的时候我们可能只想检查一下语法对不对，既能否通过前面的词法分析、语法分析，而不关心最后是否生成可执行程序，所以没必要去生成可执行程序。使用<code>cargo build</code>确实可以完成检查，不过因为<code>cargo build</code>需要生成可执行程序，所以速度会慢很多。</p>
<p>为此，<code>Cargo</code>提供了<code>cargo check</code>命令来快速检查代码的语法，该命令不会生成可执行程序。</p>
<pre class="line-numbers language-bash"><code class="language-bash">cargo clean <span class="token operator">&amp;&amp;</span> <span class="token function">time</span> cargo build
cargo clean <span class="token operator">&amp;&amp;</span> <span class="token function">time</span> cargo check
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601163739757.png" alt="cargo check比cargo build快了很多" style="zoom:33%;"></p>
<h2 id="5-把Cargo当成习惯"><a href="#5-把Cargo当成习惯" class="headerlink" title="5. 把Cargo当成习惯"></a>5. 把Cargo当成习惯</h2><p>对于简单项目，<code>Cargo</code>并不比<code>rustc</code>提供更多的优势，不过随着开发的深入，<code>Cargo</code>会越来越方便。一旦程序壮大到由多个文件组成，亦或者是需要其他的依赖，让<code>Cargo</code>协调构建过程就会简单得多。</p>
<p><code>hello_cargo</code> 这个<code>Rust</code>项目十分简单，但是却使用了很多之后我们<code>Rust</code>生涯将会用到的实用工具。</p>
<p>其实，要在任何已存在的项目上工作时，可以使用如下命令快速开始开发，爽的雅痞(*\^▽\^*)</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token function">git</span> clone example.org/someproject
<span class="token function">cd</span> someproject
cargo build
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>例如我现在用的<code>ls</code>命令的替代品<code>exa</code>就是<code>Rust</code>开发的，当然你可以在<code>APT</code>上下载预编译好的<code>exa</code>可执行文件，如果在本地编译的话速度也很快：</p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token function">git</span> clone https://github.com/ogham/exa.git
<span class="token function">cd</span> exa
cargo build
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601170924661.png" alt="首先会下载一些依赖：指定的Rust版本编译器、依赖库……" style="zoom: 25%;"></p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601170843942.png" alt="然后开始编译" style="zoom:25%;"></p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601171124247.png" alt="完成编译" style="zoom:25%;"></p>
<p>然后就得到了<code>exa</code>的可执行文件</p>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601171256785.png" alt="exa可执行文件" style="zoom:33%;"></p>
<p>接着使用<code>exa</code>看看效果</p>
<pre class="line-numbers language-bash"><code class="language-bash">./target/debug/exa -alh ./
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601171356830.png" alt="效果非常不错" style="zoom:25%;"></p>
<p>实际上，我现在的<code>ls</code>和<code>tree</code>使用的就是<code>exa</code></p>
<pre class="line-numbers language-bash"><code class="language-bash"><span class="token function">which</span> <span class="token function">ls</span>
<span class="token function">which</span> tree
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p><img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601171452622.png" alt="ls和tree都被我alias了" style="zoom:33%;"></p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Jack Wang</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://jackwang0107.github.io/2023/05/30/zhong-ke-yuan-ruan-jian-suo-shi-xi-larva-2/">https://jackwang0107.github.io/2023/05/30/zhong-ke-yuan-ruan-jian-suo-shi-xi-larva-2/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Jack Wang</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E5%AE%9E%E4%B9%A0%E6%97%A5%E8%AE%B0/">
                                    <span class="chip bg-color">实习日记</span>
                                </a>
                            
                                <a href="/tags/%E4%B8%AD%E7%A7%91%E9%99%A2/">
                                    <span class="chip bg-color">中科院</span>
                                </a>
                            
                                <a href="/tags/Rust/">
                                    <span class="chip bg-color">Rust</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.jpg" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2023/05/31/bian-yi-yuan-li-3/">
                    <div class="card-image">
                        
                        <img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/51Bv6BJig-L.jpg" class="responsive-img" alt="编译原理 3：词法分析">
                        
                        <span class="card-title">编译原理 3：词法分析</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本章是编译原理的第三章，主要对词法分析进行了介绍。
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2023-05-31
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%BC%96%E8%AF%91%E5%8E%9F%E7%90%86/" class="post-category">
                                    编译原理
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%BC%96%E8%AF%91%E5%8E%9F%E7%90%86/">
                        <span class="chip bg-color">编译原理</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2023/05/29/zhong-ke-yuan-ruan-jian-suo-shi-xi-larva-1/">
                    <div class="card-image">
                        
                        <img src="https://jack-1307599355.cos.ap-shanghai.myqcloud.com/image-20230601033238313.png" class="responsive-img" alt="中科院软件所实习日志（LARVa）：从项目开始">
                        
                        <span class="card-title">中科院软件所实习日志（LARVa）：从项目开始</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            本文是中科院软件所实习（LARVa项目）日志的第一篇，主要对实习的项目（LARVa）进行了介绍
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2023-05-29
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E4%B8%AD%E7%A7%91%E9%99%A2%E5%AE%9E%E4%B9%A0%E6%97%A5%E8%AE%B0/" class="post-category">
                                    中科院实习日记
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E5%AE%9E%E4%B9%A0%E6%97%A5%E8%AE%B0/">
                        <span class="chip bg-color">实习日记</span>
                    </a>
                    
                    <a href="/tags/%E4%B8%AD%E7%A7%91%E9%99%A2/">
                        <span class="chip bg-color">中科院</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE' || selection.getRangeAt(0).commonAncestorContainer.nodeName === 'CODE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: JackWang&#39;s Blog<br />'
            + '文章作者: Jack Wang<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('2'),
            headingSelector: 'h1, h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h1, h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\\(', '\\)']]}
    });
</script>



    <footer class="page-footer bg-color">
    

    <div class="container row center-align"
         style="margin-bottom: 15px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021-2023</span>
            
            <a href="/about" target="_blank">Jack Wang</a>
            <!-- |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a> -->
            <!-- |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a> -->
            <br>
            
                &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                        class="white-color">603.8k</span>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
                <span id="sitetime"> Loading ...</span>
                <script>
                    var calcSiteTime = function () {
                        var seconds = 1000;
                        var minutes = seconds * 60;
                        var hours = minutes * 60;
                        var days = hours * 24;
                        var years = days * 365;
                        var today = new Date();
                        var startYear = "2021";
                        var startMonth = "11";
                        var startDate = "12";
                        var startHour = "0";
                        var startMinute = "0";
                        var startSecond = "0";
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth() + 1;
                        var todayDate = today.getDate();
                        var todayHour = today.getHours();
                        var todayMinute = today.getMinutes();
                        var todaySecond = today.getSeconds();
                        var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                        var diff = t2 - t1;
                        var diffYears = Math.floor(diff / years);
                        var diffDays = Math.floor((diff / days) - diffYears * 365);

                        // 区分是否有年份.
                        var language = 'zh-CN';
                        if (startYear === String(todayYear)) {
                            document.getElementById("year").innerHTML = todayYear;
                            var daysTip = 'This site has been running for ' + diffDays + ' days';
                            if (language === 'zh-CN') {
                                daysTip = '本站已运行 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                daysTip = '本站已運行 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = daysTip;
                        } else {
                            document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                            var yearsAndDaysTip = 'This site has been running for ' + diffYears + ' years and '
                                + diffDays + ' days';
                            if (language === 'zh-CN') {
                                yearsAndDaysTip = '本站已运行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            } else if (language === 'zh-HK') {
                                yearsAndDaysTip = '本站已運行 ' + diffYears + ' 年 ' + diffDays + ' 天';
                            }
                            document.getElementById("sitetime").innerHTML = yearsAndDaysTip;
                        }
                    }

                    calcSiteTime();
                </script>
            
            <br>
            
                <span id="icp"><img src="/medias/icp.png"
                                    style="vertical-align: text-bottom;"/>
                <a href="https://beian.miit.gov.cn" target="_blank">陕ICP备2021014294号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/jackwang0108" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:2232123545@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2232123545" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2232123545" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    

    
        
        <script type="text/javascript">
            // 只在桌面版网页启用特效
            var windowWidth = $(window).width();
            if (windowWidth > 768) {
                document.write('<script type="text/javascript" src="/libs/others/sakura.js"><\/script>');
            }
        </script>
    

    <!-- 雪花特效 -->
    

    <!-- 鼠标星星特效 -->
    

     
        <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
        <script src="/libs/others/TencentCaptcha.js"></script>
        <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button>
    

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
